// src/utils/request.js
import axios from 'axios';
import { message } from 'ant-design-vue';
import { useAuthStore } from '@/stores/auth';
let authStore = null
import JSONbig from 'json-bigint';
// const parsedData = JSONbig.parse(responseText);

const baseURL = import.meta.env.VITE_REQUEST_BASE_URL
const timeout = import.meta.env.VITE_REQUEST_BASE_TIMEOUT

const service = axios.create({
    baseURL: baseURL, // 设置API的基础URL
    // timeout: timeout, // 请求超时时间
});

const instance = axios.create({
    transformResponse: [] // 清空默认的JSON转换逻辑
});

service.interceptors.response.use(response => {
    response.rawBody = response.request.responseText;
    if (response.rawBody) {
      response.data = JSONbig.parse(response.rawBody);
    }
    return response;
  });

// 请求拦截器
service.interceptors.request.use(
    config => {
        if (!authStore) authStore = useAuthStore();
        if (authStore.isLogin) config.headers[authStore.tokenName] = authStore.tokenValue;
        return config;
    },
    error => {
        // 对请求错误做些什么
        return Promise.reject(error);
    }
);

// 响应拦截器
service.interceptors.response.use(
    response => {
        const data = response.data;
        //正常
        if (data.code == 0 || (data.code>=3_000 && data.code<4_000)) {
            if (data.message != 'success'&&data.message) {
                message.success(data.message);
            }
            return data;
        }

        //...

        //业务错误
        if (data.code == 1 || (data.code >= 4_000 && data.code < 5_000)) {
            if (![4_006].includes(data.code)) {
                message.warning(data.message);
            }

            return Promise.reject(data);
        }
        //系统错误
        if (data.code >= 5_000 && data.code < 6_000) {
            message.error(data.message);
            return Promise.reject(data);
        }
    },
    error => {
        // 对响应错误做点什么
        return Promise.reject(error);
    }
);

export default service;